<template>
  <div class='users'>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span='6'>
          <el-input
            clearable
            placeholder="Please input"
            class="input-with-select"
            v-model="queryInfo.query"
            @clear='getUserList'
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>

          </el-input>
        </el-col>
        <el-col>
          <el-button
            type='primary'
            @click="dialogVisible=true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="userList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          label="索引"
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
        >
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
        >
        </el-table-column>
        <el-table-column
          prop="address"
          label="状态"
          
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change='statusChange(scope.row)'
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          width='180'
        >
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑用户"
              placement="top-start"
              :enterable='false'
              
            >
              <el-button
                class="el-icon-edit"
                type="primary"
                size='mini'
                @click="editUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top-start"
              :enterable='false'
            >
              <el-button
                class="el-icon-delete"
                type="danger"
                size='mini'
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable='false'
            >
              <el-button
                class="el-icon-setting"
                type="warning"
                size='mini'
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

    </el-card>
    <el-dialog
      title="Tips"
      :visible.sync="dialogVisible"
      width="60%"
      @close='resetForm'
    >
      <el-form
        :model="addRuleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="addRuleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            type="password"
            v-model="addRuleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="电子邮件"
          prop="email"
        >
          <el-input v-model="addRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="电话号码"
          prop="mobile"
        >
          <el-input v-model="addRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="resetForm">Cancel</el-button>
        <el-button
          type="primary"
          @click="comFirmAdd"
        >Confirm</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="请更改用户信息"
      :visible.sync="editDialogVisible"
      width="60%"
      @close='editDialogVisible=false'
    >
      <el-form
        :model="editRuleForm"
        status-icon
        :rules="rules"
        ref="editRuleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="editRuleForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="电子邮件"
          prop="email"
        >
          <el-input v-model="editRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="电话号码"
          prop="mobile"
        >
          <el-input v-model="editRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible=false">取消</el-button>
        <el-button
          type="primary"
          @click="comFirmEdit"
        >确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  components: {},
  data() {
    //电话号码的校验
    const validateMobile = (rule, value, callback) => {
          let mobileReg=/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
          if (mobileReg.test(value)) {
          return  callback();
          }
          return callback(new Error("手机格式不对"));
        };
        //邮箱的校验
        const validateEmail= (rule, value, callback) => {
          let emailReg=/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (emailReg.test(value)) {
           return callback();
          }
         return callback(new Error("电子邮箱格式不对"));
        }
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3,
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      editDialogVisible:false,
      addRuleForm:{
        username:'', password:'', email:'',
        moblie:''
      },
      editRuleForm:{
        username:'', password:'', email:'',
        moblie:''
      },
    
      rules: {
          username: [
            { required: true, message: 'Please input username', trigger: 'blur' },
            { min: 3, max: 10, message: 'Length should be 3 to 10', trigger: 'blur' }
            
          ],
          password: [
            { required: true, message: 'Please input password', trigger: 'blur' },
            { min: 5, max: 10, message: 'Length should be 5 to 10', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: 'Please input mobile', trigger: 'blur' },
            { validator:validateMobile, trigger: 'blur' }
          ],
          email:[
            { required: true, message: 'Please input email', trigger: 'blur' },
            { validator:validateEmail, trigger: 'blur' }
          ]
        }
    };
  },
  methods: {
    //一创建就请求到用户的列表
    async getUserList() {
      const { data: userList } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      console.log(userList);
      if (userList.meta.status != "200") {
        return this.$message.error("获取用户列表失败");
      }
      this.total = userList.data.total;
      this.userList = userList.data.users;
    },
    //一页展示几行
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUserList();
    },
    //改变switch状态
    async statusChange(userinfo) {
      const { data: res } = await this.$http.put(
        `/users/${userinfo.id}/state/${userinfo.mg_state}`
      );

      if (res.meta.status !== 200) {
        //如果设置失败，还要还原状态
        userinfo.mg_state != userinfo.mg_state;
        this.$message.error("设置失败");
      } else {
        this.$message({ message: "设置成功", type: "success" });
      }
    },
    //关闭表带重置输入的数据
    resetForm(){
     this.$refs.ruleForm.resetFields()
     this.dialogVisible=false;
    },
    //确定提交时的操作
    comFirmAdd(){
      this.$refs.ruleForm.validate(async (valid)=>{
          if(!valid){return}
        const  {data:res} =await this.$http.post('users',this.addRuleForm)
        console.log(res);
        if(res.meta.status=='201'){
         
          this.dialogVisible=false;
          this.getUserList();
          this.$message({
            message:'创建成功', type:'success'
          })
        }else{
          this.$message.error('创建失败')
        }
      })
    },
    editUser(userInfo){
      this.editDialogVisible=true;
      this.editRuleForm=userInfo;
      console.log(userInfo);
      
    },
    comFirmEdit(){
      this.$refs.editRuleForm.validate(async (valid)=>{
        if(!valid){return this.$message.error('修改失败');}
      const {data:res}= await this.$http.put('/users/'+this.editRuleForm.id,{
          email:this.editRuleForm.email,
          mobile:this.editRuleForm.mobile
        })
        console.log(res);
        if(res.meta.status ==200){
          this.$message.success('更改成功')
          this.editDialogVisible=false;
          this.getUserList()
          return ''
        }else{
          this.$message.success('更改失败')
          this.$message.success('更改成功')
          return ''
        }
      })
    },
    async deleteUser(id) {
         
      const res= await this.$confirm('这将会永久删除用户，确定吗?', '删除用户', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err =>err)
        if(res!=="confirm"){
            this.$message.info('删除用户操作已取消')
            return
        }else{
         const res= await this.$http.delete('/users/'+id)
         console.log(res);
         if(res.meta.status == "200"){
              this.$message.successe('删除成功');
              this.getUserList();
         }else{
           this.$message.info('删除失败');
         }
          
        }
    }
  },
  created() {
    this.getUserList();
  },
};
</script>
<style lang='scss' scoped>
.el-card {
  margin-top: 20px;
  .el-table {
    margin-top: 20px;
  }
  .el-row {
    display: flex;
  }
  .el-pagination {
    margin-top: 20px;
  }
}
</style>